package com.study.shirojwtredis.controller;

import com.alibaba.fastjson.JSON;
import com.study.shirojwtredis.domain.Account;
import com.study.shirojwtredis.domain.Message;
import com.study.shirojwtredis.shiro.filter.PasswordFilter;
import com.study.shirojwtredis.util.CommonUtil;
import com.study.shirojwtredis.util.IpUtil;
import com.study.shirojwtredis.util.JsonWebTokenUtil;
import com.study.shirojwtredis.util.RequestResponseUtil;
import io.jsonwebtoken.SignatureAlgorithm;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 *   post新增,get读取,put完整更新,patch部分更新,delete删除
 * @author tomsun28
 * @date 14:40 2018/3/8
 */
@RestController
@RequestMapping("/account")
public class AccountController extends BaseAction {

    @Autowired
    private StringRedisTemplate redisTemplate;
    /**
     * description 登录签发 JWT ,这里已经在 passwordFilter 进行了登录认证
     *
     * @param request 1
     * @param response 2
     * @return com.usthe.bootshiro.domain.vo.Message
     */
    @PostMapping("/login")
    public Message accountLogin(HttpServletRequest request, HttpServletResponse response) {
        Map<String, String> params = RequestResponseUtil.getRequestBodyMap(request);
        String appId = params.get("appId");
        // 根据appId获取其对应所拥有的角色(这里设计为角色对应资源，没有权限对应资源)
//        String roles = accountService.loadAccountRole(appId);
        String roles="user:manager";
        // 时间以秒计算,token有效刷新时间是token有效过期时间的2倍
        long refreshPeriodTime = 36000L;
        String jwt = JsonWebTokenUtil.issueJWT(UUID.randomUUID().toString(), appId,
                "token-server", refreshPeriodTime >> 1, roles, null, SignatureAlgorithm.HS512);
        // 将签发的JWT存储到Redis： {JWT-SESSION-{appID} , jwt}
        redisTemplate.opsForValue().set("JWT-SESSION-" + appId, jwt, refreshPeriodTime, TimeUnit.SECONDS);
        Account account=new Account();
        account.setAccount("123");
        account.setaId(1L);
        return new Message().ok(1003, "issue jwt success").addData("jwt", jwt).addData("user", account);
    }

    @GetMapping("/get/auth")
    public Message getAuth(HttpServletRequest request, HttpServletResponse response){
        Map<String, String> params = RequestResponseUtil.getRequestParameters(request);
        String methodName = params.get("methodName");
        if (!methodName.equals("getauth")){
            Message message = new Message();
            message.ok(1000,"issued tokenKey fail");
            return message;
        }
        /**
         * 这里可以加一些条件
         */
        //动态生成秘钥，redis存储秘钥供之后秘钥验证使用，设置有效期5秒用完即丢弃
        String tokenKey = CommonUtil.getRandomString(16);
        String userKey = CommonUtil.getRandomString(6);
        try {
            redisTemplate.opsForValue().set("TOKEN_KEY_"+ IpUtil.getIpFromRequest(WebUtils.toHttp(request)).toUpperCase()+userKey.toUpperCase(),tokenKey,10, TimeUnit.SECONDS);
            // 动态秘钥response返回给前端
            Message message = new Message();
            message.ok(1000,"issued tokenKey success")
                    .addData("tokenKey",tokenKey).addData("userKey", userKey.toUpperCase());
            return message;
        }catch (Exception e) {
            Message message = new Message();
            message.ok(1000,"issued tokenKey fail");
            return message;
        }
    }
}
